package com.example.shootinggamebackend.service.impl;

import java.util.Arrays;
import java.lang.System;
import java.util.List;
import java.util.Random;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.example.shootinggamebackend.dao.FeedBackDao;
import com.example.shootinggamebackend.entity.FeedBackPO;
import com.example.shootinggamebackend.service.TextLLMService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TextLLMServiceImpl implements TextLLMService {

    @Autowired
    FeedBackDao feedBackDao;

    private boolean initDone = false;
    private List<FeedBackPO> prizeletFBs;
    private List<FeedBackPO> jackpotFBs;
    private List<FeedBackPO> obstacleFBs;

    @Override
    public String callTextLLM(String prompt){
        if(!initDone){
            prizeletFBs = feedBackDao.getAllPrizeletFB();
            jackpotFBs = feedBackDao.getAllJackpotFB();
            obstacleFBs = feedBackDao.getAllObstacleFB();
            initDone = true;
        }

        if(prompt.contains("小奖") && !prizeletFBs.isEmpty()){
            return getRandomAndRemove(prizeletFBs).getText();
        } else if(prompt.contains("大奖") && !jackpotFBs.isEmpty()){
            return getRandomAndRemove(jackpotFBs).getText();
        } else if(prompt.contains("障碍物") && !obstacleFBs.isEmpty()){
            return getRandomAndRemove(obstacleFBs).getText();
        }

        try{
            Generation gen = new Generation();
            Message systemMsg = Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content("You are a helpful assistant.")
                    .build();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(prompt)
                    .build();
            GenerationParam param = GenerationParam.builder()
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("qwen-plus")
                    .messages(Arrays.asList(systemMsg, userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();
            String res = gen.call(param).getOutput().getChoices().get(0).getMessage().getContent();
            return res;
        } catch (ApiException e){
            System.err.println("调用文本大模型 Api 异常");
            e.printStackTrace();
        } catch (NoApiKeyException e) {
            System.err.println("调用文本大模型 Api Key 异常");
            e.printStackTrace();
        } catch (InputRequiredException e) {
            System.err.println("调用文本大模型输入异常");
            e.printStackTrace();
        }
        return "识别失败";
    }

    public static <T> T getRandomAndRemove(List<T> list) {
        if (list.isEmpty()) {
            throw new IllegalStateException("列表为空");
        }
        Random random = new Random();
        int index = random.nextInt(list.size());
        return list.remove(index);
    }

}